﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using PccCommonForC;

public partial class Manager_ProductStore_InputProductStore : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["AdminUserID"] == null)
        {
            Response.Write("<script language=javascript>alert('Time is out.');window.open('../Default.aspx','_top');</script>");
            return;
        }
        if (!IsPostBack)
        {
            BindRate(ddlOriginalRate);
            BindStoreList();
            CountStoreProduct();
            lblTotalStore.Text = lblQuantity.Text;
            BindData();
        }
        else
        {
            if (Request.QueryString["Type"] == "2")
            {
                if (hidMethod.Value.Trim() != "")
                {
                    PccMsg msg = new PccMsg("<PccMsg>" + hidMethod.Value + "</PccMsg>");
                    if (msg.Query("Method") == "LoadCalendar")
                    {
                        LoadCalendar(msg.Query("Date"));
                    }
                    hidMethod.Value = "";
                }
            }
        }       
       
        SetState();

 
    }



    private void LoadCalendar(string sDate)
    {
        clsWebShop cls = new clsWebShop();
        clsCommon clsCom = new clsCommon();
       
        DataTable dt= cls.GetData("SELECT top 1 * 		FROM [HNB].[dbo].[Store_Product] where  Note_MK='PLUS' AND PDID='" + Request.QueryString["PDID"] + "' and left(OriginalDate,8)=left(" + Calendar1.Text.Replace("/", "") + ",8) 		Order By OriginalDate desc").Tables[0];
        if (dt.Rows.Count > 0)
        {
            txtOriginalPrice.Text =   clsCom.FormatMoney(dt.Rows[0]["OriginalPrice"].ToString());
            hidSPDID.Value = dt.Rows[0]["SPDID"].ToString();
            if (dt.Rows[0]["OriginalDate"].ToString().Trim() != "")
                Calendar1.Text = dt.Rows[0]["OriginalDate"].ToString().Substring(0, 4) + "/" + dt.Rows[0]["OriginalDate"].ToString().Substring(4, 2) + "/" + dt.Rows[0]["OriginalDate"].ToString().Substring(6, 2);
            try
            {
                ddlOriginalRate.SelectedItem.Selected = false;
                ddlOriginalRate.Items.FindByValue(dt.Rows[0]["OriginalRate"].ToString()).Selected = true;
            }
            catch { }
            txtOriginalPrice.ReadOnly = false;
            txtOriginalPrice.BackColor = System.Drawing.Color.White;
            btnAdd_Catalogue.Visible = true;
        }
        else
        {
            txtOriginalPrice.Text = "0";
            if (Request.QueryString["Type"] == "2")
            {
                txtOriginalPrice.ReadOnly = true;
                txtOriginalPrice.BackColor = System.Drawing.Color.FromName("#eaeaea");
                btnAdd_Catalogue.Visible = false;
                ClientScript.RegisterClientScriptBlock(this.GetType(), "", "<script>alert('Giá gốc chưa cập nhật trong ngày này')</script>");
            }
           
        }
    }

    private void BindStoreList()
    {
        clsWebShop cls = new clsWebShop();
        ListItem item = new ListItem();
        ddlStore.DataSource = cls.Get_StoreByKindNoNoneProc().Tables[0];
        ddlStore.DataTextField = "StName";
        ddlStore.DataValueField = "StID";
        ddlStore.DataBind();
        item.Text = "--Tất cả--";
        item.Value = "0";
        ddlStore.Items.Insert(0, item);
        ddlStore.SelectedItem.Selected = false;

        try
        {
            if (Request.QueryString["StID"] != "" && Request.QueryString["StID"] != null)
                ddlStore.Items.FindByValue(Request.QueryString["StID"]).Selected = true;
        }
        catch { }


    }


    private void BindRate(DropDownList ddl)
    {
        ListItem item = new ListItem();
        item.Text = "VNĐ";
        item.Value = "VNĐ";
        item.Selected = true;
        ddl.Items.Add(item);
        item = new ListItem();
        item.Text = "USD";
        item.Value = "USD";
        ddl.Items.Add(item);
    }


    private void BindData()
    {
        clsCommon clsCom = new clsCommon();
        Calendar1.Text = DateTime.Now.ToString("yyyy/MM/dd");
        if (Request.QueryString["PDID"] != "" && Request.QueryString["PDID"] != null)
        {
            clsWebShop cls = new clsWebShop();
            PccMsg msg = new PccMsg();
            msg.CreateFirstNode("PdID", Request.QueryString["PDID"]);
            //DataTable dt = cls.Get_ProductByProductID(msg.GetXmlStr.ToString()).Tables[0];
            DataTable dt = cls.GetData("select B.OriginalPrice,B.OriginalRate,A.PdName,A.PdID,B.OriginalDate,A.Price,A.Rate from product A left join Store_Product B on A.PDID=B.PDID where A.PDID='" + Request.QueryString["PDID"] + "'").Tables[0];
            if (dt.Rows.Count > 0)
            {
                lblPDID.Text = dt.Rows[0]["PDID"].ToString();
                lblPDNm.Text = dt.Rows[0]["PDName"].ToString();
                lblPriceOut.Text = clsCom.FormatMoney(dt.Rows[0]["Price"].ToString());
                lblRateOut.Text = dt.Rows[0]["Rate"].ToString();

                Calendar1.Text = System.DateTime.Now.ToString("yyyy/MM/dd");
                LoadCalendar(Calendar1.Text.Replace("/", ""));
                
                //lblQuantity.Text=dt.Rows[0]["Quantity"].ToString();
                // lblQuantity.Text = CountStoreProduct();
            }
        }
        if (Request.QueryString["Type"] == "0")
        {
            lblTitleQuantity.Text = "<font color='red'>Số lượng xuất kho</font>";
        }

        if (ddlStore.SelectedValue == "0")
        {
            txtInput.Text = "0";
            txtInput.ReadOnly = true;
            txtInput.BackColor = System.Drawing.Color.FromName("#eaeaea");
        }
        else
        {
            txtInput.ReadOnly = false;
            txtInput.BackColor = System.Drawing.Color.White;

        }
        
    }

    private void ReturnPage()
    {
        // Response.Redirect("ProductStore.aspx?KindNo=" + Request.QueryString["KindNo"] + "&CodeID=" + Request.QueryString["CodeID"] + "&PageIndex=" + Request.QueryString["PageIndex"]);
        ClientScript.RegisterClientScriptBlock(this.GetType(), "", "<script>parent.fnBindData('ProductStore.aspx?KindNo=" + Request.QueryString["KindNo"] + "&CodeID=" + Request.QueryString["CodeID"] + "&PageIndex=" + Request.QueryString["PageIndex"] + "')</script>");
    }
    protected void btnAdd_Catalogue_Click(object sender, EventArgs e)
    {
        clsCommon clsCom = new clsCommon();
        PccMsg msg = new PccMsg();
        string PDID = Request.QueryString["PDID"];
        string sDate = Calendar1.Text.Replace("/", "") + System.DateTime.Now.ToString("hhmmss");
        string sRate = ddlOriginalRate.SelectedValue;
        string sPrice=txtOriginalPrice.Text.Replace(",", "");
        if (Request.QueryString["PDID"] != "" && Request.QueryString["PDID"] != null)
        {       
            if (Request.QueryString["Type"] == "2")
            {
                if (clsCom.ConvertToDecimal(lblTotalStore.Text) > 0)
                {
                    msg = new PccMsg();
                    msg.CreateFirstNode("PDID", PDID);
                    msg.CreateFirstNode("SPdID", hidSPDID.Value);
                    msg.CreateFirstNode("OriginalPrice", sPrice);
                    msg.CreateFirstNode("OriginalRate", sRate);
                    msg.CreateFirstNode("OriginalDate",sDate );
                    clsWebShop cls = new clsWebShop();
                    string xml = cls.Upd_OriginalPrice(msg.GetXmlStr.ToString());
                }
            }
            else
            {
                if (ddlStore.SelectedValue != "0") //GIA GOC
                {
                    if (clsCom.ConvertToDecimal(txtInput.Text) <= 0)
                    {
                        ClientScript.RegisterClientScriptBlock(this.GetType(), "", "<script>alert('Nhập vào số lượng kho')</script>");
                        return;
                    }
                    string Note_MK = "PLUS";
                    if (Request.QueryString["Type"] == "0")
                    {
                        if (int.Parse(txtInput.Text) > int.Parse(lblQuantity.Text))
                        {
                            ClientScript.RegisterClientScriptBlock(this.GetType(), "", "<script>alert('Số lượng cập nhập lớn hơn số lượng trong kho " + ddlStore.SelectedItem.Text + "!!!')</script>");
                            return;
                        }
                        Note_MK = "SUBSTRACT";
                        msg.CreateFirstNode("Output", txtInput.Text);
                    }
                    else if (Request.QueryString["Type"] == "1")
                    {
                        msg.CreateFirstNode("Input", txtInput.Text);
                    }

                    msg.CreateFirstNode("PDID", PDID);
                    msg.CreateFirstNode("StID", ddlStore.SelectedValue);
                    msg.CreateFirstNode("OriginalPrice", sPrice);
                    msg.CreateFirstNode("OriginalRate", sRate);
                    msg.CreateFirstNode("OriginalDate", sDate);
                    msg.CreateFirstNode("Note", txtNote.Text);
                    msg.CreateFirstNode("Note_MK", Note_MK);
                    msg.CreateFirstNode("UpdID", Session["AdminUserID"].ToString());
                    msg.CreateFirstNode("flag", Request.QueryString["Type"]);

                    clsWebShop cls = new clsWebShop();
                    string xml = cls.Ins_Store_Product(msg.GetXmlStr.ToString());
                    msg = new PccMsg(xml);
                    if (msg.Query("strOutput") == "-2")
                    {
                        ClientScript.RegisterClientScriptBlock(this.GetType(), "", "<script>alert('Số lượng cập nhập lớn hơn số lượng trong kho " + ddlStore.SelectedItem.Text + "!!!')</script>");
                        return;
                    }
                }
            }
            ReturnPage();
        }
    }
    protected void btnReturn_Click(object sender, EventArgs e)
    {
        ReturnPage();
    }
    private void CountStoreProduct()
    {
        clsWebShop cls = new clsWebShop();
        lblQuantity.Text = cls.Get_CountStorerByPDIDCondition(ddlStore.SelectedValue, Request.QueryString["PDID"]);
        if (lblQuantity.Text == "")
            lblQuantity.Text = "0";
    }
    protected void ddlStore_SelectedIndexChanged(object sender, EventArgs e)
    {
        CountStoreProduct();
        SetState();
        //BindData();
    }

    private void SetState()
    {

        if (Request.QueryString["Type"] == "0" || Request.QueryString["Type"] == "1")
        {
            Calendar1.Visible = false;
            if (ddlStore.SelectedValue != "0")
            {
                txtInput.ReadOnly = false;
                txtInput.BackColor = System.Drawing.Color.White;

                if (Request.QueryString["Type"] != "0") //xuat kho khong cho thay doi gia
                {
                    txtOriginalPrice.ReadOnly = false;
                    txtOriginalPrice.BackColor = System.Drawing.Color.White;

                    ddlOriginalRate.Enabled = true;
                }
                else
                {
                    txtOriginalPrice.ReadOnly = true;
                    txtOriginalPrice.BackColor = System.Drawing.Color.FromName("#eaeaea");

                    ddlOriginalRate.Enabled = false;
                }
            }
            else
            {
                txtInput.ReadOnly = true;
                txtInput.BackColor = System.Drawing.Color.FromName("#eaeaea");

                txtOriginalPrice.ReadOnly = true;
                txtOriginalPrice.BackColor = System.Drawing.Color.FromName("#eaeaea");

                ddlOriginalRate.Enabled = false;
            }
        }
        else
        {
            tr1.Visible = false;
            tr2.Visible = false;
            tr3.Visible = false;
            tr4.Visible = true;
        }

        
    }


}
